<template>
  <div class="resource-list">
    <JLForm
      ref="formRef"
      class="search-from"
      :form-config="formConfig"
      :form-data="formData"
      :form-item-config="formItemConfig"
    >
      <template #searchSlot>
        <el-button color="#0560FD" @click="search">查询</el-button>
      </template>
    </JLForm>
    <div class="main-option">
      <el-button class="up-resource" color="#0560FD" @click="onEdit()"
        ><SvgIcon icon-class="add" />上传资源</el-button
      >
    </div>
    <div style="display: none">{{ tableData }}</div>
    <JLDatagrid
      :data="tableData"
      :table-config="tableConfig"
      :column-config="tableColumn"
      :page-config="pageConfig"
      @pageCurrentChange="pageCurrentChange"
      @pageSizeChange="pageSizeChange"
    >
      <template #resCoverSlot="{ row }">
        <el-image v-if="row.resCover" :src="retFilePath(row.resCover)" class="avatar" />
        <img v-else src="@/assets/png/default-bg.png" />
      </template>
      <template #handleStateSlot="{ row }">
        <div @click="onOption(row)" :class="getStateClass(row)">
          {{ stateMap.get(row.handleState) || '' }}
        </div>
      </template>
      <template #uploadTimeSlot="{ row }">
        <div>{{ dayjs(row.uploadTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
      </template>

      <template #fileSizeSlot="{ row }">
        <div>{{ transferMb(row.fileSize) }}Mb</div>
      </template>
      <template #slotOperation="{ row }">
        <div class="table-btn-wrap">
          <el-button type="text" class="btn" @click="onPreview(row)" :disabled="judgeDisable(row)"
            >预览</el-button
          >
          <el-button
            type="text"
            class="btn"
            @click="onEdit(row)"
            :disabled="!(row.handleState === 53 || row.handleState === 63)"
            >编辑</el-button
          >
          <el-button type="text" class="btn" @click="onDelete(row)">删除</el-button>
        </div>
      </template>
    </JLDatagrid>

    <Total :num="pageConfig.total" />
    <CreateDialog
      :resource="selRow"
      v-if="createDialogShow"
      :is-re-upload="isReUpload"
      @close-handle="createCloseHandle"
    ></CreateDialog>
  </div>
</template>

<script setup lang="ts">
import { mergerFile } from '@/api/common';
import { deleteResource, reProcess } from '@/api/resource';
import { IResource } from '@/api/resource/types';
import Total from '@/components/pagination/total.vue';
import { confirmAgain, retFilePath, transferMb } from '@/utils';
import CreateDialog from '@/views/resource/create/index.vue';
import { JLDatagrid, JLForm } from '@jl/element-plus';
import { messageUtil } from '@jl/element-plus/utils';
import { dayjs } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { list } from './composables/list';

defineOptions({
  name: 'ResourceList',
});

const router = useRouter();

const {
  formRef,
  formConfig,
  formData,
  formItemConfig,
  tableRef,
  pageConfig,
  tableConfig,
  tableColumn,
  tableData,
  search,
  pageCurrentChange,
  pageSizeChange,
} = list();

const createDialogShow = ref(false);
const selRow = ref<null | IResource>(null);

const stateMap = new Map([
  [1, '处理中'],
  [2, '完成'],
  [3, '失败'],
  [21, '继续上传'], // 等待上传
  [22, '继续上传'], // 等待合并

  [23, '处理中'], // 合并中
  [24, '处理中'], // 完成合并
  [25, '重新转换'], // 合并失败

  [32, '处理中'], // 解压缩中
  [33, '处理中'], // 完成解压
  [34, '重新转换'], // 解压失败

  [42, '处理中'], // 数据处理中
  [43, '完成处理'], // 完成处理
  [44, '重新转换'], // 处理失败

  [52, '处理中'], // 传输中
  [53, '完成'], // 传输完成
  [54, '重新转换'], // 传输失败

  [63, '完成'], // 发布成功
  [64, '处理失败'], // 发布失败
]);
const getStateClass = (row: any) => {
  if (row.handleState === 53 || row.handleState === 63) {
    return 'option-state-success';
  } else if (stateMap.get(row.handleState) === '处理中') {
    return 'option-state-running';
  } else if (row.handleState === 21 || row.handleState === 22) {
    return 'option-state-reupload';
  } else {
    return 'option-state-reoption';
  }
};

const judgeDisable = (row: any) => {
  if (['osgb'].includes(row.fileType) && row.configJson) {
    const configJson = JSON.parse(row.configJson);
    if (!configJson.IsChange) {
      return true;
    }
  }
  if (['tif_dom', 'tif_dem'].includes(row.fileType)) {
    if (!row.configJson) {
      return true;
    }
  }
  if (['terrain'].includes(row.fileType)) {
    return true;
  }
  if (row.handleState === 53 || row.handleState === 63) {
    return false;
  }
  return true;
};

const createCloseHandle = (refresh: boolean) => {
  createDialogShow.value = false;
  search(refresh);
};

onMounted(() => {
  search();
});

function onPreview(item: IResource) {
  if (
    !['gltf', '_3dtiles', 'tif_dem', 'tif_dom', 'shp', 'kml', 'json', 'jlg'].includes(item.fileType)
  ) {
    return;
  }
  if (![63, 53].includes(item.handleState)) {
    messageUtil.warning('资源正在处理中，无法加载');
    return;
  }
  router.push({
    path: `/resource/preview/${item.resourceId}`,
  });
}

async function onDelete(item: IResource) {
  const flag = await confirmAgain('确认删除该资源数据？', '删除操作不可逆，删除后将撤销展示。');
  if (!flag) return;
  deleteResource({ params: { resId: item.resourceId } }).then(() => {
    messageUtil.success('删除成功');
    search(true);
  });
}

function onEdit(item?: IResource) {
  isReUpload.value = false;
  selRow.value = item || null;
  createDialogShow.value = true;
}
const isReUpload = ref(false);
async function onOption(item: IResource) {
  if ([21, 22, 23].includes(item.handleState)) {
    // 上传失败，合并失败走重新上传的逻辑
    isReUpload.value = true;
    selRow.value = item || null;
    createDialogShow.value = true;
  } else if (item.handleState === 25) {
    await mergerFile({ transId: item.transId });
    search(false);
  } else {
    const fData = new FormData();
    fData.set('resourceId', item.resourceId);
    const param = {
      data: fData,
    };
    await reProcess(param);
    search(false);
  }
}
</script>

<style lang="less" scoped>
.resource-list {
  position: relative;

  :deep(.total) {
    position: absolute;
    left: 0;
    bottom: 0;
  }
}

.search-btn {
  text-align: right;
}
.option-state-success {
  position: relative;
  color: #161616;
  font-size: 14px;
  padding-left: 16px;
  &::before {
    content: '';
    width: 7px;
    height: 7px;
    left: 0;
    background-color: #00f763;
    top: 50%;
    transform: translateY(-50%);
    position: absolute;
    border-radius: 4px;
  }
}

.option-state-reupload {
  color: #0560fd;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}
.option-state-reoption {
  color: #0560fd;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}
.option-state-running {
  position: relative;
  color: #161616;
  font-size: 14px;
  padding-left: 16px;
  &::before {
    content: '';
    width: 7px;
    height: 7px;
    left: 0;
    background-color: #faad14;
    top: 50%;
    transform: translateY(-50%);
    position: absolute;
    border-radius: 4px;
  }
}
.el-image {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}
.up-resource {
  .svg-icon {
    margin-right: 7px;
    font-size: 12px;
  }
}
</style>
